package com.happy.controller;


import com.happy.entity.OptionEntity;
import com.happy.entity.SubjectEntity;
import com.happy.service.IOptionService;
import com.happy.service.ISubjectService;
import com.happy.util.ResultBody;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping ("/subject")
@CrossOrigin (value = "*", maxAge = 3600)
public class SubjectController {


    @Resource
    private ISubjectService iSubjectService;
    @Resource
    private IOptionService iOptionService;

    @RequestMapping ("/queryList")
    public ResultBody<SubjectEntity> queryList (@RequestBody SubjectEntity subjectEntity) {
        List<SubjectEntity> subjectEntities = iSubjectService.queryList ( subjectEntity );
        int totalCount = iSubjectService.totalCount ( subjectEntity );
        return ResultBody.success ( subjectEntities, totalCount );
    }

    /**
     * 新增一道题目
     * @param subjectEntity
     * @return
     */
    @RequestMapping ("addSingle")
    public ResultBody<SubjectEntity> addSingle (@RequestBody SubjectEntity subjectEntity) {
        subjectEntity = iSubjectService.addSingle ( subjectEntity );
        return ResultBody.success (subjectEntity);
    }

    /**
     * 批量增加题目的选项
     * 1、新增当前题目的四个选项
     * 2、修改当前题目的正确选项
     * @param subjectEntity
     * @return
     */
    @RequestMapping ("/addOptionList")
    public ResultBody<SubjectEntity> addOptionList (@RequestBody SubjectEntity subjectEntity) {
        List<OptionEntity> optionEntities = subjectEntity.getOptionEntities ();
        for ( OptionEntity optionEntity : optionEntities ) {
            optionEntity.setSubjectId ( subjectEntity.getSubjectId () );
            optionEntity.setCreateTime ( new Date () );
            if ( optionEntity.getOptionId () == subjectEntity.getOptionId () ) {
                int insert = iOptionService.getBaseMapper ().insert ( optionEntity );
                subjectEntity.setOptionId ( optionEntity.getOptionId () ); // 将添加成功的正确选项设置给当前题目
                subjectEntity = iSubjectService.updateSingle ( subjectEntity );
            } else {
                int insert = iOptionService.getBaseMapper ().insert ( optionEntity ); // 添加其他非正确选项
            }
        }
        return ResultBody.success ( subjectEntity );
    }

}
